package com.xxx.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.idev.excel.FastExcel;
import com.xxx.springboot.listener.BaseExcelListener;
import com.xxx.springboot.pojo.bean.UserDO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * alibaba fastexcel导入导出
 */
@RestController
@RequestMapping("/excel")
public class FastExcelController {

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户清单", "UTF-8");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 写入数据
        FastExcel.write(response.getOutputStream(), UserDO.class)
                .sheet("模板")
                .doWrite(getUserList());
    }

    // 创建测试数据
    private List<UserDO> getUserList() throws IOException {
        List<UserDO> userList = new ArrayList<>();
        Date now = new Date();
        for(int i=1; i<=10; i++) {
            UserDO dto = new UserDO();
            dto.setId((long)i);
            dto.setUsername("用户" + i);
            dto.setNickname("昵称" + i);
            dto.setBirthday(DateUtil.offsetDay(now, i));
            dto.setPhone("1860001000" + i);
            dto.setHeight(1.73);
            dto.setGender(1);
            userList.add(dto);
        }
        return userList;
    }

    // Excel读取功能
    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择一个文件上传！");
        }
        try {
            // 读取excel数据
            BaseExcelListener<UserDO> baseExcelListener = new BaseExcelListener<>();
            FastExcel.read(file.getInputStream(), UserDO.class, baseExcelListener).sheet().doRead();
            List<UserDO> dataList = baseExcelListener.getDataList();
            System.out.println(dataList);
            return ResponseEntity.ok("文件上传并处理成功！");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件处理失败！");
        }
    }

}